<template>
  <div class="qr-generator-tool">
    <div class="tool-header">
      <h1>二维码生成器</h1>
      <p>快速生成各种样式的二维码</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 输入区域 -->
        <el-col :span="12">
          <div class="input-section">
            <div class="section-header">
              <h3>输入内容</h3>
              <div class="actions">
                <el-button @click="clearInput" size="small">清空</el-button>
                <el-button @click="pasteFromClipboard" size="small" type="primary">粘贴</el-button>
              </div>
            </div>
            
            <el-input
              v-model="inputText"
              type="textarea"
              :rows="6"
              placeholder="请输入要生成二维码的内容（文本、网址、联系方式等）..."
              @input="handleInput"
            />
            
            <div class="input-stats" v-if="inputText">
              <el-tag type="info" size="small">字符数: {{ inputText.length }}</el-tag>
            </div>
          </div>

          <!-- 样式设置 -->
          <div class="settings-section">
            <h3>样式设置</h3>
            
            <div class="setting-item">
              <label>尺寸大小:</label>
              <el-slider
                v-model="qrSize"
                :min="100"
                :max="500"
                :step="10"
                show-input
                @change="generateQR"
              />
            </div>
            
            <div class="setting-item">
              <label>前景色:</label>
              <el-color-picker
                v-model="foregroundColor"
                @change="generateQR"
                show-alpha
              />
            </div>
            
            <div class="setting-item">
              <label>背景色:</label>
              <el-color-picker
                v-model="backgroundColor"
                @change="generateQR"
                show-alpha
              />
            </div>
            
            <div class="setting-item">
              <label>容错级别:</label>
              <el-select v-model="errorCorrectionLevel" @change="generateQR">
                <el-option label="L (7%)" value="L" />
                <el-option label="M (15%)" value="M" />
                <el-option label="Q (25%)" value="Q" />
                <el-option label="H (30%)" value="H" />
              </el-select>
            </div>
          </div>
        </el-col>

        <!-- 输出区域 -->
        <el-col :span="12">
          <div class="output-section">
            <div class="section-header">
              <h3>二维码预览</h3>
              <div class="actions">
                <el-button @click="downloadQR" size="small" :disabled="!qrCodeUrl" type="primary">下载</el-button>
                <el-button @click="copyQR" size="small" :disabled="!qrCodeUrl">复制图片</el-button>
              </div>
            </div>
            
            <div class="qr-preview" v-if="qrCodeUrl">
              <img :src="qrCodeUrl" :alt="'二维码: ' + inputText" class="qr-image" />
            </div>
            
            <div class="qr-placeholder" v-else>
              <el-icon :size="60"><Picture /></el-icon>
              <p>二维码将在这里显示</p>
            </div>
            
            <div class="qr-info" v-if="qrCodeUrl">
              <el-tag type="success" size="small">生成成功</el-tag>
              <el-tag type="info" size="small">尺寸: {{ qrSize }}x{{ qrSize }}px</el-tag>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 快速生成按钮 -->
      <div class="quick-actions">
        <el-button-group>
          <el-button @click="generateQR" :disabled="!inputText" type="primary">
            <el-icon><Picture /></el-icon>
            生成二维码
          </el-button>
          <el-button @click="generateWithDefault" :disabled="!inputText">
            <el-icon><Refresh /></el-icon>
            重置样式
          </el-button>
        </el-button-group>
      </div>

      <!-- 使用说明 -->
      <div class="tool-info">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>使用说明</span>
            </div>
          </template>
          
          <div class="info-content">
            <h4>支持的内容类型：</h4>
            <ul>
              <li><strong>网址：</strong>https://www.example.com</li>
              <li><strong>文本：</strong>任意文本内容</li>
              <li><strong>联系方式：</strong>电话、邮箱等</li>
              <li><strong>WiFi信息：</strong>WIFI:T:WPA;S:网络名;P:密码;;</li>
              <li><strong>地理位置：</strong>geo:纬度,经度</li>
            </ul>
            
            <h4>容错级别说明：</h4>
            <ul>
              <li><strong>L (7%)：</strong>适合高质量环境</li>
              <li><strong>M (15%)：</strong>推荐使用</li>
              <li><strong>Q (25%)：</strong>适合一般环境</li>
              <li><strong>H (30%)：</strong>适合恶劣环境</li>
            </ul>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Picture, Refresh } from '@element-plus/icons-vue'

const inputText = ref('')
const qrCodeUrl = ref('')
const qrSize = ref(200)
const foregroundColor = ref('#000000')
const backgroundColor = ref('#ffffff')
const errorCorrectionLevel = ref('M')

const handleInput = () => {
  if (inputText.value.trim()) {
    generateQR()
  } else {
    qrCodeUrl.value = ''
  }
}

const generateQR = () => {
  if (!inputText.value.trim()) {
    ElMessage.warning('请输入要生成二维码的内容')
    return
  }
  
  try {
    // 使用在线QR码生成API
    const params = new URLSearchParams({
      data: inputText.value,
      size: qrSize.value + 'x' + qrSize.value,
      format: 'png',
      ecc: errorCorrectionLevel.value,
      color: foregroundColor.value.replace('#', ''),
      bgcolor: backgroundColor.value.replace('#', '')
    })
    
    qrCodeUrl.value = `https://api.qrserver.com/v1/create-qr-code/?${params.toString()}`
    ElMessage.success('二维码生成成功')
  } catch (error) {
    ElMessage.error('生成失败：' + error.message)
  }
}

const generateWithDefault = () => {
  qrSize.value = 200
  foregroundColor.value = '#000000'
  backgroundColor.value = '#ffffff'
  errorCorrectionLevel.value = 'M'
  generateQR()
}

const clearInput = () => {
  inputText.value = ''
  qrCodeUrl.value = ''
  ElMessage.info('已清空输入内容')
}

const downloadQR = () => {
  if (!qrCodeUrl.value) {
    ElMessage.warning('没有可下载的二维码')
    return
  }
  
  const link = document.createElement('a')
  link.href = qrCodeUrl.value
  link.download = `qrcode-${Date.now()}.png`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  ElMessage.success('二维码下载完成')
}

const copyQR = async () => {
  if (!qrCodeUrl.value) {
    ElMessage.warning('没有可复制的二维码')
    return
  }
  
  try {
    const response = await fetch(qrCodeUrl.value)
    const blob = await response.blob()
    await navigator.clipboard.write([
      new ClipboardItem({ 'image/png': blob })
    ])
    ElMessage.success('二维码已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败，请尝试下载')
  }
}

const pasteFromClipboard = async () => {
  try {
    const text = await navigator.clipboard.readText()
    inputText.value = text
    generateQR()
    ElMessage.success('已粘贴内容并生成二维码')
  } catch (error) {
    ElMessage.error('无法访问剪贴板，请手动粘贴')
  }
}

onMounted(() => {
  // 组件挂载后的初始化
})
</script>

<style scoped>
.qr-generator-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.input-section,
.output-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  height: 100%;
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.actions {
  display: flex;
  gap: 8px;
}

.input-stats {
  margin-top: 15px;
  display: flex;
  gap: 10px;
}

.settings-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
}

.settings-section h3 {
  color: #333;
  margin-bottom: 20px;
  font-size: 1.2rem;
}

.setting-item {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 15px;
}

.setting-item label {
  min-width: 80px;
  font-weight: 500;
  color: #333;
}

.setting-item .el-slider {
  flex: 1;
}

.setting-item .el-color-picker {
  margin-left: auto;
}

.qr-preview {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 2px dashed #ddd;
}

.qr-image {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.qr-placeholder {
  text-align: center;
  padding: 40px 20px;
  color: #999;
  background: #f8f9fa;
  border-radius: 8px;
  border: 2px dashed #ddd;
}

.qr-placeholder p {
  margin-top: 10px;
  font-size: 0.9rem;
}

.qr-info {
  margin-top: 15px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.quick-actions {
  margin: 30px 0;
  text-align: center;
}

.tool-info {
  margin-top: 40px;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.info-content h4 {
  color: #333;
  margin: 20px 0 10px 0;
  font-size: 1.1rem;
}

.info-content ul {
  color: #666;
  padding-left: 20px;
  margin-bottom: 15px;
}

.info-content li {
  margin-bottom: 5px;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .setting-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .setting-item label {
    min-width: auto;
  }
}
</style>
